package org.adl.registry.website;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import org.adl.registry.website.rim.RimSearchResponseParser;

/**
 *
 * @author Jacob Marks - Joint ADL Co-Lab
 * @version 1.0
 * @license This software is licensed as open source software pursuant to the terms defined in the Joint ADL Co-Lab Open Source Software License.  Use of any part of this software constitutes acceptance of this license. The Joint ADL Co-Lab open source agreement is available at {@link http://adlregistry.adlnet.gov/source_license.html}.
 */
public class RequestProcessor
{
    public static String doSearch(HttpServletRequest iRequest, HttpServletResponse iResponse, JspWriter iOut, ServletContext iContext)
    {
        String rimResponse = "";
        
        // Determine what action has been requested.
        String action = iRequest.getParameter("action");
        String a = "noaction";
        if (action != null)
        {
            a = action;
        }
        
        try
        {
            // Make request to RIM.
            if (a.equalsIgnoreCase("basicsearch"))
            {
                // Process a basic search request.
                
                String contentType = iRequest.getContentType();
                
                if ("multipart/form-data".equalsIgnoreCase(contentType))
                {
                    ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.INVALID_REQUEST_102);
                }
                else
                {
                    BasicSearchRequest handler = new BasicSearchRequest(iRequest, iContext);
                    
                    rimResponse = handler.InvokeRequest();
                }
            }
            else if (a.equalsIgnoreCase("advancedsearch"))
            {
                // Process an advanced search request.
                
                String contentType = iRequest.getContentType();
                
                if ("multipart/form-data".equalsIgnoreCase(contentType))
                {
                    ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.INVALID_REQUEST_102);
                }
                else
                {
                    AdvancedSearchRequest handler = new AdvancedSearchRequest(iRequest, iContext);
                    
                    rimResponse = handler.InvokeRequest();
                }
            }
            else
            {
                GenericSearchRequest handler = new GenericSearchRequest(iRequest, iContext);
                
                rimResponse = handler.InvokeRequest();
            }
            
            if (rimResponse.length() > 0)
            {
                // Display RIM response to the user.
                if (rimResponse.contains("<RIM "))
                {
                    // RIM error encountered.  Parse error information.
                    ErrorHandler.ProcessRIMError(iResponse, iContext, rimResponse);
                }
                else
                {
                    // Result must be a search result.
                    boolean responseTypeUsed = PortalUtil.getUseRimResponseTypeParameter(iContext);
                    
                    if (responseTypeUsed)
                    {
                        // The request sent tot RIM used the RIM response type parameter and is assumed to be HTML.
                        rimResponse = rimResponse.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
                    }
                    else
                    {
                        // The request sent tot RIM did not used the RIM response type parameter and is assumed to be XML.
                        try
                        {
                            // Get the RIM search response xsl.
                            String installPath = System.getenv("REGISTRY_WEBSITE_HOME");
                            String xslPath = installPath + PortalUtil.getSearchResponseXSLPath(iContext, iRequest.getParameter("registry"));
                            File xslFile = new File(xslPath);
                            if (xslFile.exists() == false)
                            {
                                throw new FileNotFoundException("The RIM search response stylesheet could not be found.");
                            }
                            FileInputStream xslInput = new FileInputStream(xslFile);
                            
                            rimResponse = rimResponse.replace("http://www.adlregistry.dtic.mil/xsd/adlregistry-query-response", "");
                            rimResponse = rimResponse.replace("http://www.adlregistry.dtic.mil/xsd/adlregistry-query-response ", "");
                            rimResponse = rimResponse.replace("http://hdl.cordra.net/2000.2.1/adlregistry-query-response?VData=version&#38;id=2", "");
                            
                            // Convert the String xml input into an InputStream.
                            ByteArrayInputStream xmlInput = new ByteArrayInputStream(rimResponse.getBytes());
                            
                            ByteArrayOutputStream output = new ByteArrayOutputStream();
                            
                            StreamResult transformResult = new StreamResult(output);
                            
                            RimSearchResponseParser.transform(xmlInput, xslInput, transformResult);
                            
                            rimResponse = output.toString();
                        }
                        catch (TransformerConfigurationException ex)
                        {
                            ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.GENERAL_ERROR_203, ex);
                        }
                        catch (FileNotFoundException ex)
                        {
                            ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.GENERAL_ERROR_201, ex);
                        }
                        catch (TransformerException ex)
                        {
                            ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.GENERAL_ERROR_204, ex);
                        }
                    }
                }
            }
        }
        catch (IOException ex)
        {
            ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.INVALID_REQUEST_103, ex);
        }
        catch (InvalidRequestException ex)
        {
            ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.INVALID_REQUEST_104, ex);
        }
        
        return rimResponse;
    }
    
    public static String doGetMetadata(HttpServletRequest iRequest, HttpServletResponse iResponse, JspWriter iOut, ServletContext iContext)
    {
        String rimResponse = "";
        
        String contentType = iRequest.getContentType();
        try
        {
            
            if ("multipart/form-data".equalsIgnoreCase(contentType))
            {
                ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.INVALID_REQUEST_101);
            }
            else
            {
                RetrieveMetadataXmlRequest handler = new RetrieveMetadataXmlRequest(iRequest, iContext);
                
                rimResponse = handler.InvokeRequest();
            }
            
            if (rimResponse.length() > 0)
            {
                // Display RIM response to the user.
                if (rimResponse.contains("<RIM "))
                {
                    // RIM error encountered.  Parse error information.
                    ErrorHandler.ProcessRIMError(iResponse, iContext, rimResponse);
                }
                else
                {
                    // Result must be a search result.
                    boolean responseTypeUsed = PortalUtil.getUseRimResponseTypeParameter(iContext);
                    
                    if (responseTypeUsed)
                    {
                        // The request sent tot RIM used the RIM response type parameter and is assumed to be HTML.
                        rimResponse = rimResponse.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
                    }
                    else
                    {
                        // The request sent tot RIM did not used the RIM response type parameter and is assumed to be XML.
//                        try
//                        {
//                            // Get the RIM search response xsl.
//                            String installPath = System.getenv("REGISTRY_WEBSITE_HOME");
//                            String xslPath = installPath + PortalUtil.getSearchResponseXSLPath(iContext, iRequest.getParameter("registry"));
//                            File xslFile = new File(xslPath);
//                            if (xslFile.exists() == false)
//                            {
//                                throw new FileNotFoundException("The RIM search response stylesheet could not be found.");
//                            }
//                            FileInputStream xslInput = new FileInputStream(xslFile);
//                            
//                            rimResponse = rimResponse.replace("http://www.adlregistry.dtic.mil/xsd/adlregistry-query-response", "");
//                            rimResponse = rimResponse.replace("http://www.adlregistry.dtic.mil/xsd/adlregistry-query-response ", "");
//                            rimResponse = rimResponse.replace("http://hdl.cordra.net/2000.2.1/adlregistry-query-response?VData=version&#38;id=2", "");
//                            
//                            // Convert the String xml input into an InputStream.
//                            ByteArrayInputStream xmlInput = new ByteArrayInputStream(rimResponse.getBytes());
//                            
//                            ByteArrayOutputStream output = new ByteArrayOutputStream();
//                            
//                            StreamResult transformResult = new StreamResult(output);
//                            
//                            RimSearchResponseParser.transform(xmlInput, xslInput, transformResult);
//                            
//                            rimResponse = output.toString();
//                        }
//                        catch (TransformerConfigurationException ex)
//                        {
//                            ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.GENERAL_ERROR_205, ex);
//                        }
//                        catch (FileNotFoundException ex)
//                        {
//                            ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.GENERAL_ERROR_202, ex);
//                        }
//                        catch (TransformerException ex)
//                        {
//                            ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.GENERAL_ERROR_206, ex);
//                        }
                    }
                }
            }
        }
        catch (InvalidRequestException ex)
        {
            ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.INVALID_REQUEST_105, ex);
        }
        catch (IOException ex)
        {
            ErrorHandler.ProcessGeneralError(iResponse, iContext, ErrorHandler.INVALID_REQUEST_106, ex);
        }
        
        return rimResponse;
    }
}
